package org.mspring.platform.weibo.tencent;

import java.io.IOException;
import java.util.Date;

import javax.annotation.PostConstruct;

import org.mspring.platform.weibo.tencent.dao.TencentUserinfoDao;
import org.mspring.platform.weibo.tencent.entity.TencentUserinfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author Gao Youbo
 * @since 2014年5月19日
 */
@Service
@Transactional
public class TencentUserinfoService {

    private static final Logger log = LoggerFactory.getLogger(TencentUserinfoService.class);
    @Autowired
    private TencentUserinfoDao tencentAuthDao;

    @PostConstruct
    public void initTable() {
        try {
            tencentAuthDao.initTable();
        } catch (IOException e) {
            log.error("初始化表失败", e);
        }
    }

    public void insertOrUpdate(long user, String openid, String openkey, String accessToken, String refreshToken, long expiresIn) {
        TencentUserinfo auth = findByUserId(user);
        if (auth == null) {
            auth = new TencentUserinfo();
            auth.setCreateTime(new Date());
        }
        auth.setUserId(user);
        auth.setOpenid(openid);
        auth.setOpenkey(openkey);
        auth.setAccessToken(accessToken);
        auth.setRefreshToken(refreshToken);
        auth.setExpiresIn(expiresIn);
        auth.setSuccess(true);
        tencentAuthDao.merge(auth);
    }

    /**
     * 设置是否授权成功
     *
     * @param user
     * @param success
     */
    public void setSuccess(long user, boolean success) {
        TencentUserinfo auth = findByUserId(user);
        if (auth == null) {
            log.warn("无法完成设置，未找到用户授权信息. userId = ", user);
            return;
        }
        auth.setSuccess(success);
        tencentAuthDao.update(auth);
    }

    public TencentUserinfo findByUserId(long user) {
        return tencentAuthDao.getBy("userId", user);
    }
}
